<template>
  <j-modal
    :title="editId ? '编辑模板' : '新增模板'"
    :width="1200"
    :visible.sync="modalVisible"
    :maskClosable="false"
    switchFullscreen
  >
    <a-spin :spinning="submitLoading">
      <!-- 主表单区域 -->
      <a-form-model ref="form" :model="formData" :rules="rules">
        <a-row>
          <a-col :span="24">
            <a-form-model-item label="模板名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="templateName">
              <a-input v-model="formData.templateName" placeholder="请输入模板名称" :maxLength="128"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-button type="primary" icon="plus" @click="addQualityItem">添加质检项</a-button>
        <a-table
          :pagination="false"
          bordered
          :columns="formColumns"
          :data-source="formData.hzArchiveQualityItermList"
          rowKey="sortNum"
          style="margin-top: 20px"
          ref="qualityTable"
        >
          <template #sortSlot>
            <a-icon type="menu" class="sort-handler-ico" title="拖动排序" />
          </template>
          <template #itemTitle> <span class="required-ico">*</span>质检项 </template>
          <template #itemSlot="text, record, index">
            <a-form-model-item
              :prop="'hzArchiveQualityItermList.' + index + '.item'"
              :rules="{
                required: true,
                message: '质检项不能为空',
                trigger: 'blur',
              }"
            >
              <a-textarea v-model="record.item" rows="3" placeholder="请输入质检项" :maxLength="50" />
            </a-form-model-item>
          </template>
          <template #standarTitle> <span class="required-ico">*</span>质检标准 </template>
          <template #standarSlot="text, record, index">
            <a-form-model-item
              :prop="'hzArchiveQualityItermList.' + index + '.standar'"
              :rules="{
                required: true,
                message: '质检标准不能为空',
                trigger: 'blur',
              }"
            >
              <a-textarea v-model="record.standar" rows="3" placeholder="请输入质检标准" :maxLength="200" />
            </a-form-model-item>
          </template>
          <span slot="action" slot-scope="text, record, index">
            <a-button type="link" @click="delQualityItem(index)">删除</a-button>
          </span>
        </a-table>
      </a-form-model>
    </a-spin>
    <template #footer>
      <a-button @click="modalVisible = false"> 取消 </a-button>
      <a-button type="primary" :loading="submitLoading" @click="submit"> 保存 </a-button>
    </template>
  </j-modal>
</template>

<script>
import Sortable from 'sortablejs'
import { getAction, postAction } from '@/api/manage'

export default {
  name: 'ArchiveQualityTemplateModal',
  props: {
    // 要编辑的产品档案id，为空表示新增
    editId: {
      type: String,
      default: '',
    },
    // 是否显示弹框
    visible: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      modalVisible: this.visible,
      submitLoading: false,
      formData: {
        templateName: '',
        hzArchiveQualityItermList: [],
      },
      rules: {
        templateName: [{ required: true, message: '请输入模板名称!' }],
      },
      url: {
        add: '/hzkj-product/product/archive/hzArchiveQualityTemplate/add',
        edit: '/hzkj-product/product/archive/hzArchiveQualityTemplate/edit',
        queryById: '/hzkj-product/product/archive/hzArchiveQualityTemplate/queryById',
        queryListById: '/hzkj-product/product/archive/hzArchiveQualityTemplate/queryHzArchiveQualityItermByMainId',
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      formColumns: [
        {
          title: '排序',
          width: 60,
          align: 'center',
          scopedSlots: { customRender: 'sortSlot' },
        },
        {
          title: '序号',
          width: 60,
          align: 'center',
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          },
        },
        {
          align: 'center',
          width: 350,
          slots: { title: 'itemTitle' },
          scopedSlots: { customRender: 'itemSlot' },
        },
        {
          align: 'center',
          width: 550,
          slots: { title: 'standarTitle' },
          scopedSlots: { customRender: 'standarSlot' },
        },
        {
          title: '操作',
          align: 'center',
          scopedSlots: { customRender: 'action' },
        },
      ],
    }
  },
  watch: {
    modalVisible(val) {
      this.$emit('update:visible', val)
    },
  },
  methods: {
    getInfo() {
      return new Promise((resolve) => {
        getAction(this.url.queryById, { id: this.editId }).then((res) => {
          if (res.success) {
            resolve(res.result)
          } else {
            this.$message.warning(res.message)
          }
        })
      })
    },
    getList() {
      return new Promise((resolve) => {
        getAction(this.url.queryListById, { id: this.editId }).then((res) => {
          if (res.success) {
            resolve(res.result)
          } else {
            this.$message.warning(res.message)
          }
        })
      })
    },
    addQualityItem() {
      this.formData.hzArchiveQualityItermList.push({
        sortNum: new Date().getTime(),
        item: '',
        standar: '',
      })
    },
    delQualityItem(index) {
      this.formData.hzArchiveQualityItermList.splice(index, 1)
    },
    submit() {
      this.$refs.form.validate((pass) => {
        if (!pass) {
          return
        }
        if (this.formData.hzArchiveQualityItermList.length == 0) {
          this.$message.error('请至少添加一个质检项')
          return
        }
        this.submitLoading = true
        postAction(this.editId ? this.url.edit : this.url.add, {
          ...this.formData,
          hzArchiveQualityItermList: this.formData.hzArchiveQualityItermList.map((item, index) => ({
            ...item,
            sortNum: index + 1, // 确保排序号从1开始
          })),
        })
          .then((res) => {
            if (res.success) {
              this.$message.success(`${this.editId ? '编辑' : '新增'}成功`)
              this.modalVisible = false // 关闭弹框
              this.$emit('submit', res.result) // 通知父组件提交成功
            } else {
              this.$message.error(res.message)
            }
          })
          .finally(() => {
            this.submitLoading = false
          })
      })
    },
  },
  created() {
    if (this.editId) {
      // 编辑，需要回显
      this.submitLoading = true
      Promise.all([this.getInfo(), this.getList()]).then(([resInfo, resList]) => {
        this.formData = {
          ...resInfo,
          hzArchiveQualityItermList: resList
            .sort((a, b) => a.sortNum - b.sortNum)
            .map((item, index) => ({
              ...item,
              sortNum: index + 1, // 确保排序号从1开始
            })),
        }
        this.submitLoading = false
      })
    }
  },
  mounted() {
    //初始化表格拖动
    this.$nextTick(() => {
      console.log(this.$refs.qualityTable)
      new Sortable(this.$refs.qualityTable.$el.querySelector('tbody'), {
        handle: '.sort-handler-ico',
        animation: 200,
        sort: true,
        onEnd: ({ newIndex, oldIndex }) => {
          //  oldIndex:谁
          //  newIndex:移动到哪儿
          const currRow = this.formData.hzArchiveQualityItermList.splice(oldIndex, 1)[0]
          this.formData.hzArchiveQualityItermList.splice(newIndex, 0, currRow)
        },
      })
    })
  },
}
</script>

<style scoped lang="less">
.required-ico {
  margin-right: 4px;
  color: #f5222d;
  font-size: 14px;
}
.sort-handler-ico {
  padding: 10px;
  cursor: move;
}
</style>
